<template>
  <div class="account">
    <div class="form-wrap">
      <form-list
        ref="formRef"
        layout="vertical"
        :model="formData"
        :rules="formRules"
        @finish="onFinish"
        @finishFailed="onFinishFailed"
        ><form-item
          label="用户名"
          name="username"
          :rules="[{ required: true, validator: validatePhone }]"
        >
          <a-input
            v-model:value="formData.username"
            :disabled="input_disabled.username"
            placeholder="请输入手机号"
          />
        </form-item>
        <form-item label="密码" name="password">
          <!-- <a-input
            v-model:value="formData.password"
            placeholder="请输入密码"
            type="password"
          /> -->
          <a-input-password
            v-model:value="formData.password"
            placeholder="请输入密码"
          >
            <template #prefix>
              <LockOutlined class="site-form-item-icon" />
            </template>
          </a-input-password>
        </form-item>
        <form-item
          label="确认密码"
          name="confirm"
          :rules="[{ required: true, validator: confirmPass }]"
        >
          <a-input
            v-model:value="formData.confirm"
            placeholder="请再次输入密码"
            type="password"
          />
        </form-item>
        <form-item label="验证码" name="Code">
          <div class="code">
            <a-input
              v-model:value="formData.Code"
              placeholder="请输入六位验证码"
            />
            <a-button
              type="primary"
              :disabled="disabled_code_button"
              :loading="button_loading"
              @click="getCode"
              >{{ button_text }}</a-button
            >
          </div>
        </form-item>
        <form-item>
          <a-button type="primary" class="btn" html-type="submit"
            >注册</a-button
          >
          <a-button class="btn">滑动验证</a-button>
          <div class="warn">
            <router-link to="/forget"> 忘记密码 </router-link>
            <router-link to="/login"> 登录 </router-link>
          </div>
        </form-item>
      </form-list>
    </div>
  </div>
</template>
<script>
  import { useRouter } from "vue-router"
  import { defineComponent, reactive, toRefs, ref, onMounted } from "vue"
  import { UserOutlined, LockOutlined } from "@ant-design/icons-vue"
  import { message } from "ant-design-vue"
  import { formRules } from "@/utils/fromRules"
  import { checkUserName, getSanCode } from "@/api/account"
  export default defineComponent({
    components: {
      UserOutlined,
      LockOutlined,
    },

    setup() {
      const router = useRouter()
      // 數據
      const input_disabled = reactive({
        username: false,
      })
      const formData = reactive({
        username: "",
        password: "",
        confirm: "",
        Code: "",
      })

      const dataItem = reactive({
        // 获取验证码按钮
        button_text: "获取验证码",
        button_loading: false,
        disabled_code_button: true,
        sec: 0,
        // 定时器
        timer: null,
      })

      // 解构后， 我们就不需要 用 对象.属性了， 而是可以直接使用属性，来简化
      const form = toRefs(formData)
      const data = toRefs(dataItem)
      // 二次驗證密碼
      let confirmPass = async (_rule, value) => {
        if (value === "") {
          return Promise.reject("請再次輸入密碼")
        } else if (value !== formData.password) {
          return Promise.reject("兩次密碼輸入不一致!")
        } else {
          return Promise.resolve()
        }
      }
      // 手機號碼驗證
      const validatePhone = (aaa, value, callback) => {
        let reg = /^1[34578]\d{9}$/
        if (value === "" || value === undefined || value === null) {
          return Promise.reject("手机号码格式错误")
        } else {
          if (!reg.test(value)) {
            dataItem.disabled_code_button = true
            return Promise.reject(new Error("手机号码格式错误"))
          } else {
            // checkName()
            dataItem.disabled_code_button = false
            return Promise.resolve()
          }
        }
      }
      // 验证用户名api
      const checkName = () => {
        input_disabled.username = true
        checkUserName({ username: formData.username })
          .then((res) => {
            input_disabled.username = false
            dataItem.disabled_code_button = false
            return Promise.resolve(res)
          })
          .catch(() => {
            input_disabled.username = false
            dataItem.disabled_code_button = true
          })
      }

      // 方法
      const onFinish = (values) => {
        console.log("Success:", values)
      }
      const onFinishFailed = (errorInfo) => {
        console.log("Failed:", errorInfo)
      }
      // 獲取驗證碼
      const getCode = async () => {
        await checkName()
        // 按钮加载
        dataItem.button_loading = true
        const data = {
          username: formData.username,
          type: "Register",
        }
        const { error_code, msg, content } = await getSanCode(data)
        // console.log(result)
        if (error_code === 0) {
          message.success(`${msg} ${content}`)
        }
        // 按钮文本
        dataItem.button_text = "发送中"
        countDown()
        dataItem.button_text = `重新获取`
        // 按钮激活
        dataItem.disabled_code_button = false
      }
      // 倒計時
      const countDown = () => {
        // 更新時間
        dataItem.sec = 10
        // 优先判断定时器是否存在，存在则先清除后再开启
        dataItem.timer && clearInterval(dataItem.timer)
        dataItem.timer = setInterval(() => {
          const s = dataItem.sec--
          dataItem.button_text = `${s}秒`
          dataItem.disabled_code_button = true
          if (s <= 0) {
            clearInterval(dataItem.timer)
            dataItem.button_text = `重新获取`
            // 按钮激活
            dataItem.disabled_code_button = false
            dataItem.button_loading = false
          }
        }, 1000)
      }
      // 生命週期
      onMounted(() => {})
      // return
      return {
        formData,
        router,
        formRules,
        onFinish,
        onFinishFailed,
        confirmPass,
        dataItem,
        ...form,
        ...data,
        getCode,
        validatePhone,
        input_disabled,
      }
    },
  })
</script>
<style lang="scss" scoped>
  @import "./style.scss";
</style>
